<template>
  <div>
    <div class="marquee-container" ref="container" @mouseenter="pause" @mouseleave="resume">
      <div 
        class="marquee-content" 
        :class="{ 'marquee-animation': shouldScroll }"
        :style="contentStyle"
        ref="content"
      >
        <span class="marquee-text">欢迎您,{{ userName }},使用system</span>
        <span v-if="shouldScroll" class="marquee-text">欢迎您,{{ userName }},使用system</span>
      </div>
    </div>
  </div>
</template>

<script>
import storages from '@/until/localStorage';
export default {
  name: 'Marquee',
  data() {
    return {
      userName: storages.getItem('userName'),
      speed: 20,
      shouldScroll: false,
      containerWidth: 0,
      contentWidth: 0
    }
  },
  computed: {
    contentStyle() {
      return {
        animationDuration: `${this.speed}s`,
        width: `${this.contentWidth * (this.shouldScroll ? 2 : 1)}px`
      }
    }
  },
  mounted() {
    // console.log(JSON.parse(storages.getItem('routerList')));
    
    this.calculateWidth()
    window.addEventListener('resize', this.calculateWidth)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateWidth)
  },
  methods: {
    calculateWidth() {
      this.$nextTick(() => {
        const container = this.$refs.container
        const content = this.$refs.content
        if (container && content) {
          this.containerWidth = container.offsetWidth
          this.contentWidth = content.firstChild.offsetWidth
          this.shouldScroll = this.contentWidth > this.containerWidth
        }
      })
    },
    pause() {
      if (this.shouldScroll) {
        this.$refs.content.style.animationPlayState = 'paused'
      }
    },
    resume() {
      if (this.shouldScroll) {
        this.$refs.content.style.animationPlayState = 'running'
      }
    }
  },
  watch: {
    text() {
      this.calculateWidth()
    }
  }
}
</script>

<style scoped>
.marquee-container {
  overflow: hidden;
  white-space: nowrap;
  margin: 90px auto;
  text-align: center;
  width: 100%;
  height: 100px;
  font-size: 50px;
}

.marquee-content {
  display: inline-block;
  white-space: nowrap;
}

.marquee-text {
  display: inline-block;
  padding-right: 2em; /* 防止文字首尾相接 */
  color: #f00;
}

.marquee-animation {
  animation: marquee linear infinite;
}

@keyframes marquee {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-50%);
  }
}
</style>
